import { Student } from '../types/student';
import { getFormattedCurrentDateTime, validateEmail, validatePhone } from '../utils/helpers';

class StudentManager {
    private students: Student[] = [];
    private keyword: string = '';

    constructor() {
        this.loadStudentsFromLocalStorage();
        this.renderTable();
        this.bindEvents();
    }

    // 加载本地存储的学生数据
    loadStudentsFromLocalStorage() {
        const data = localStorage.getItem('student-data');
        if (data) {
            this.students = JSON.parse(data);
        } else {
            // 如果没有数据，初始化一些示例数据
            this.students = [
                {
                    id: 1,
                    name: 'Alice',
                    gender: 'Female',
                    hobbies: 'Reading',
                    email: 'alice@example.com',
                    phone: '12345678901',
                    age: 20,
                    create_at: getFormattedCurrentDateTime(),
                    update_at: getFormattedCurrentDateTime(),
                },
                {
                    id: 2,
                    name: 'Bob',
                    gender: 'Male',
                    hobbies: 'Sports',
                    email: 'bob@example.com',
                    phone: '10987654321',
                    age: 22,
                    create_at: getFormattedCurrentDateTime(),
                    update_at: getFormattedCurrentDateTime(),
                },
            ];
            this.saveStudentsToLocalStorage();
        }
    }

    // 保存学生数据到本地存储
    saveStudentsToLocalStorage() {
        localStorage.setItem('student-data', JSON.stringify(this.students));
    }

    // 渲染学生表格
    renderTable() {
        const tbody = document.querySelector('.studentTable tbody') as HTMLElement;
        tbody.innerHTML = '';

        const filteredStudents = this.keyword
            ? this.students.filter((student) =>
                student.name.toLowerCase().includes(this.keyword.toLowerCase())
            )
            : this.students;

        filteredStudents.forEach((student) => {
            const row = document.createElement('tr');

            row.innerHTML = `
        <td><input type="checkbox" class="selectStudent" data-id="${student.id}"></td>
        <td>${student.id}</td>
        <td>${student.name}</td>
        <td>${student.gender}</td>
        <td>${student.hobbies}</td>
        <td>${student.email}</td>
        <td>${student.phone}</td>
        <td>${student.age}</td>
        <td>${student.create_at}</td>
        <td>${student.update_at}</td>
        <td>
          <button class="editBtn" data-id="${student.id}">Edit</button>
          <button class="deleteBtn" data-id="${student.id}">Delete</button>
        </td>
      `;

            tbody.appendChild(row);
        });
    }

    // 绑定事件
    bindEvents() {
        // 添加学生按钮
        const openModalBtn = document.querySelector('.openModalBtn') as HTMLButtonElement;
        openModalBtn.addEventListener('click', () => this.openAddModal());

        // 搜索按钮
        const searchBtn = document.querySelector('.searchBtn') as HTMLButtonElement;
        searchBtn.addEventListener('click', () => this.searchStudents());

        // 全选复选框
        const selectAllCheckbox = document.querySelector('.selectAll') as HTMLInputElement;
        selectAllCheckbox.addEventListener('change', (e) => this.selectAllStudents(e));

        // 表格中的编辑和删除按钮
        const tbody = document.querySelector('.studentTable tbody') as HTMLElement;
        tbody.addEventListener('click', (e) => this.handleTableActions(e));

        // 表单提交
        const studentForm = document.querySelector('.studentForm') as HTMLFormElement;
        studentForm.addEventListener('submit', (e) => this.handleFormSubmit(e));

        // 模态框关闭事件
        window.addEventListener('click', (e) => this.closeModal(e));
    }

    // 打开添加学生的模态框
    openAddModal() {
        const modal = document.querySelector('.studentModal') as HTMLElement;
        const modalTitle = document.querySelector('.modalTitle') as HTMLElement;
        const studentForm = document.querySelector('.studentForm') as HTMLFormElement;

        modalTitle.textContent = 'Add New Student';
        studentForm.reset();
        (studentForm.querySelector('.studentIdToEdit') as HTMLInputElement).value = '';

        modal.style.display = 'block';
    }

    // 打开编辑学生的模态框
    openEditModal(id: number) {
        const student = this.students.find((s) => s.id === id);
        if (!student) return;

        const modal = document.querySelector('.studentModal') as HTMLElement;
        const modalTitle = document.querySelector('.modalTitle') as HTMLElement;
        const studentForm = document.querySelector('.studentForm') as HTMLFormElement;

        modalTitle.textContent = 'Edit Student';
        (studentForm.querySelector('.studentIdToEdit') as HTMLInputElement).value = student.id.toString();
        (studentForm.querySelector('.studentName') as HTMLInputElement).value = student.name;
        (studentForm.querySelector('.studentGender') as HTMLSelectElement).value = student.gender;
        (studentForm.querySelector('.studentHobbies') as HTMLInputElement).value = student.hobbies;
        (studentForm.querySelector('.studentEmail') as HTMLInputElement).value = student.email;
        (studentForm.querySelector('.studentPhone') as HTMLInputElement).value = student.phone;
        (studentForm.querySelector('.studentAge') as HTMLInputElement).value = student.age.toString();

        modal.style.display = 'block';
    }

    // 关闭模态框
    closeModal(e: Event) {
        const modal = document.querySelector('.studentModal') as HTMLElement;
        if (e.target === modal) {
            modal.style.display = 'none';
        }
    }

    // 处理表格中的编辑和删除操作
    handleTableActions(e: Event) {
        const target = e.target as HTMLElement;
        const id = parseInt(target.getAttribute('data-id') || '0', 10);
        if (target.classList.contains('editBtn')) {
            this.openEditModal(id);
        } else if (target.classList.contains('deleteBtn')) {
            this.deleteStudent(id);
        } else if (target.classList.contains('selectStudent')) {
            this.checkBoxSelectedHandler()
        }
    }

    // 表单提交处理
    handleFormSubmit(e: Event) {
        e.preventDefault();
        const studentForm = e.target as HTMLFormElement;

        const id = (studentForm.querySelector('.studentIdToEdit') as HTMLInputElement).value;
        const name = (studentForm.querySelector('.studentName') as HTMLInputElement).value.trim();
        const gender = (studentForm.querySelector('.studentGender') as HTMLSelectElement).value;
        const hobbies = (studentForm.querySelector('.studentHobbies') as HTMLInputElement).value.trim();
        const email = (studentForm.querySelector('.studentEmail') as HTMLInputElement).value.trim();
        const phone = (studentForm.querySelector('.studentPhone') as HTMLInputElement).value.trim();
        const age = parseInt((studentForm.querySelector('.studentAge') as HTMLInputElement).value, 10);

        // 验证输入
        if (!name || !gender || !hobbies || !email || !phone || !age) {
            alert('Please fill in all fields.');
            return;
        }

        if (!validateEmail(email)) {
            alert('Invalid email format.');
            return;
        }

        if (!validatePhone(phone)) {
            alert('Invalid phone number format.');
            return;
        }

        if (id) {
            // 编辑学生
            const student = this.students.find((s) => s.id === parseInt(id, 10));
            if (student) {
                student.name = name;
                student.gender = gender;
                student.hobbies = hobbies;
                student.email = email;
                student.phone = phone;
                student.age = age;
                student.update_at = getFormattedCurrentDateTime();
            }
        } else {
            // 添加新学生
            const newStudent: Student = {
                id: this.students.length ? this.students[this.students.length - 1].id + 1 : 1,
                name,
                gender,
                hobbies,
                email,
                phone,
                age,
                create_at: getFormattedCurrentDateTime(),
                update_at: getFormattedCurrentDateTime(),
            };
            this.students.push(newStudent);
        }

        this.saveStudentsToLocalStorage();
        this.renderTable();
        const modal = document.querySelector('.studentModal') as HTMLElement;
        modal.style.display = 'none';
    }

    // 删除学生
    deleteStudent(id: number) {
        if (confirm('Are you sure you want to delete this student?')) {
            this.students = this.students.filter((s) => s.id !== id);
            this.saveStudentsToLocalStorage();
            this.renderTable();
        }
    }

    // 搜索学生
    searchStudents() {
        const keywordInput = document.querySelector('.keyword') as HTMLInputElement;
        this.keyword = keywordInput.value.trim();
        this.renderTable();
    }

    // 全选/取消全选学生
    selectAllStudents(e: Event) {
        const checked = (e.target as HTMLInputElement).checked;
        const checkboxes = document.querySelectorAll('.selectStudent') as NodeListOf<HTMLInputElement>;
        checkboxes.forEach((checkbox) => (checkbox.checked = checked));
    }

    checkBoxSelectedHandler() {
        console.log('checkBoxSelectedHandler');

        let stuAllLen = this.students.length

        let stusAllEl: NodeListOf<HTMLInputElement> = document.querySelectorAll('.selectStudent')
        // console.log(stusAllEl);
        let checkedStuNum = 0
        stusAllEl.forEach(element => {
            console.log(element);
            if (element.checked) {
                checkedStuNum++
            }

        });

        if (stuAllLen === checkedStuNum) {
            (document.querySelector('.selectAll') as HTMLInputElement).checked = true
        } else {
            (document.querySelector('.selectAll') as HTMLInputElement).checked = false
        }

        console.log(checkedStuNum);

        // stusAllEl.filter(item => {
        //   console.log(item);

        // })
    }
}

document.addEventListener('DOMContentLoaded', () => {
    new StudentManager();
});